using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MVCWeekOne.Models;
using System.Text.Json;

namespace MVCWeekOne.Controllers
{
    /// <summary>
    /// 生产计划管理控制器
    /// </summary>
    public class PlanController : Controller
    {
        private readonly HttpClient _httpClient;
        private readonly ApiSettings _apiSettings;

        public PlanController(IHttpClientFactory httpClientFactory, IOptions<ApiSettings> apiSettings)
        {
            _httpClient = httpClientFactory.CreateClient();
            _apiSettings = apiSettings.Value;
            
            // 配置HttpClient超时
            _httpClient.Timeout = TimeSpan.FromSeconds(_apiSettings.TimeoutSeconds);
        }

        /// <summary>
        /// 生产计划列表页面
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Index()
        {
            var plans = new List<PlanDto>();

            try
            {
                // 调用API获取生产计划列表
                var response = await _httpClient.GetAsync($"{_apiSettings.ReadApiUrl}/Plan/page?index=1&size=20");
                
                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonSerializer.Deserialize<ApiPageing<PlanDto>>(jsonContent);
                    
                    if (apiResult != null && apiResult.Code == 200)
                    {
                        plans = apiResult.Items;
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录错误日志
                ViewBag.Error = $"获取生产计划列表失败：{ex.Message}";
            }

            return View(plans);
        }

        /// <summary>
        /// 获取生产计划明细（AJAX调用）
        /// </summary>
        /// <param name="planId">计划ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetPlanItems(int planId)
        {
            try
            {
                // 调用API获取计划明细
                var response = await _httpClient.GetAsync($"{_apiSettings.ReadApiUrl}/Plan/{planId}/items");
                
                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonSerializer.Deserialize<ApiResult<List<PlanItemDto>>>(jsonContent);
                    
                    if (apiResult != null && apiResult.IsSuccess)
                    {
                        return Json(new { success = true, data = apiResult.Data });
                    }
                    else
                    {
                        return Json(new { success = false, message = apiResult?.Msg ?? "获取明细失败" });
                    }
                }
                else
                {
                    return Json(new { success = false, message = $"API调用失败：{response.StatusCode}" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取计划明细失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取生产计划详情（包括计划信息和明细）
        /// </summary>
        /// <param name="planId">计划ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetPlanDetail(int planId)
        {
            try
            {
                // 调用API获取计划详情（包含明细）
                var response = await _httpClient.GetAsync($"{_apiSettings.ReadApiUrl}/Plan/{planId}");
                
                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonSerializer.Deserialize<ApiResult<PlanDetailDto>>(jsonContent, new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
                    
                    if (apiResult != null && apiResult.IsSuccess && apiResult.Data != null)
                    {
                        var planDetail = apiResult.Data;
                        
                        // 分离计划信息和明细信息
                        var planInfo = new
                        {
                            id = planDetail.Id,
                            code = planDetail.Code,
                            remark = planDetail.Remark,
                            createBy = planDetail.CreateBy,
                            createTime = planDetail.CreateTime,
                            updateBy = planDetail.UpdateBy,
                            updateTime = planDetail.UpdateTime
                        };
                        
                        return Json(new { 
                            success = true, 
                            plan = planInfo, 
                            items = planDetail.Items 
                        });
                    }
                    else
                    {
                        return Json(new { success = false, message = apiResult?.Msg ?? "获取计划详情失败" });
                    }
                }
                else
                {
                    return Json(new { success = false, message = $"API调用失败：{response.StatusCode}" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取计划详情失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// API测试页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Test()
        {
            return View();
        }



        /// <summary>
        /// 保存生产计划
        /// </summary>
        /// <param name="planData">生产计划数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SavePlan([FromBody] SavePlanRequest planData)
        {
            try
            {
                // 构建保存命令 - 使用新的Products字段
                var commandProducts = new List<object>();
                if (planData.Products != null && planData.Products.Any())
                {
                    foreach (var product in planData.Products)
                    {
                        commandProducts.Add(new
                        {
                            Id = product.Id, // 产品ID（0表示新增，>0表示更新）
                            PlanId = planData.Id, // 绑定到当前计划ID
                            ProductCode = product.ProductCode,
                            ProductName = product.ProductName,
                            Spec = product.Spec,
                            Unit = product.Unit,
                            Producer = product.Producer,
                            ProductionStartTime = product.ProductionStartTime,
                            ProductionEndTime = product.ProductionEndTime,
                            IsRemoved = product.IsRemoved
                        });
                    }
                }
                else if (planData.Items != null && planData.Items.Any())
                {
                    // 向后兼容：如果没有Products字段但有Items字段，转换为Products格式
                    foreach (var item in planData.Items)
                    {
                        commandProducts.Add(new
                        {
                            Id = item.Id,
                            PlanId = planData.Id,
                            ProductCode = item.ProductCode,
                            ProductName = item.ProductName,
                            Spec = item.Spec,
                            Unit = (string?)null,
                            Producer = (string?)null,
                            ProductionStartTime = DateTime.Now,
                            ProductionEndTime = DateTime.Now.AddDays(1),
                            IsRemoved = item.IsDeleted
                        });
                    }
                }

                var command = new
                {
                    Id = planData.Id, // 关键：编辑时需要带上计划ID
                    Code = planData.Code,
                    Remark = planData.Remark,
                    OperateBy = "系统管理员", // 这里可以从用户会话中获取
                    Products = commandProducts // 使用Products字段
                };

                // 调用写API保存
                var response = await _httpClient.PostAsJsonAsync($"{_apiSettings.WriteApiUrl}/Plan/save", command);
                
                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonSerializer.Deserialize<ApiResult<int>>(jsonContent, new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
                    
                    if (apiResult != null && apiResult.IsSuccess)
                    {
                        return Json(new { success = true, message = "保存成功", data = apiResult.Data });
                    }
                    else
                    {
                        return Json(new { success = false, message = apiResult?.Msg ?? "保存失败" });
                    }
                }
                else
                {
                    return Json(new { success = false, message = $"API调用失败：{response.StatusCode}" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"保存失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 导出生产计划
        /// </summary>
        /// <param name="exportData">导出参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Export([FromBody] ExportPlanRequest exportData)
        {
            try
            {
                var command = new
                {
                    PlanIds = exportData.PlanIds,
                    OperateBy = exportData.OperateBy ?? "系统管理员"
                };

                // 调用写API导出
                var response = await _httpClient.PostAsJsonAsync($"{_apiSettings.WriteApiUrl}/Plan/export", command);
                
                if (response.IsSuccessStatusCode)
                {
                    var fileBytes = await response.Content.ReadAsByteArrayAsync();
                    var fileName = $"生产计划导出_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx";
                    
                    return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
                }
                else
                {
                    return BadRequest($"导出失败：{response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                return BadRequest($"导出失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 导入生产计划
        /// </summary>
        /// <param name="file">Excel文件</param>
        /// <param name="operateBy">操作人</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Import(IFormFile file, [FromForm] string operateBy)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return Json(new { success = false, message = "请选择要导入的文件" });
                }

                // 检查文件类型
                var allowedExtensions = new[] { ".xlsx", ".xls" };
                var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
                if (!allowedExtensions.Contains(fileExtension))
                {
                    return Json(new { success = false, message = "只支持Excel文件格式(.xlsx, .xls)" });
                }

                // 构建multipart表单数据
                using var formData = new MultipartFormDataContent();
                using var fileStream = file.OpenReadStream();
                using var streamContent = new StreamContent(fileStream);
                streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                formData.Add(streamContent, "file", file.FileName);
                formData.Add(new StringContent(operateBy ?? "系统管理员"), "operateBy");

                // 调用写API导入
                var response = await _httpClient.PostAsync($"{_apiSettings.WriteApiUrl}/Plan/import", formData);
                
                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonSerializer.Deserialize<ApiResult<object>>(jsonContent, new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
                    
                    if (apiResult != null && apiResult.IsSuccess)
                    {
                        return Json(new { success = true, message = "导入成功" });
                    }
                    else
                    {
                        return Json(new { success = false, message = apiResult?.Msg ?? "导入失败" });
                    }
                }
                else
                {
                    return Json(new { success = false, message = $"导入失败：{response.StatusCode}" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"导入失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 下载导入模板
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ImportTemplate()
        {
            try
            {
                // 调用写API获取模板
                var response = await _httpClient.GetAsync($"{_apiSettings.WriteApiUrl}/Plan/import-template");
                
                if (response.IsSuccessStatusCode)
                {
                    var fileBytes = await response.Content.ReadAsByteArrayAsync();
                    var fileName = "生产计划导入模板.xlsx";
                    
                    return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
                }
                else
                {
                    return BadRequest($"获取模板失败：{response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                return BadRequest($"获取模板失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 批量删除生产计划
        /// </summary>
        /// <param name="deleteData">删除参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> BatchDelete([FromBody] BatchDeletePlanRequest deleteData)
        {
            try
            {
                var command = new
                {
                    PlanIds = deleteData.PlanIds,
                    OperateBy = deleteData.OperateBy ?? "系统管理员"
                };

                // 调用写API批量删除
                var request = new HttpRequestMessage(HttpMethod.Delete, $"{_apiSettings.WriteApiUrl}/Plan/batch-delete")
                {
                    Content = JsonContent.Create(command)
                };
                
                var response = await _httpClient.SendAsync(request);
                
                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonSerializer.Deserialize<ApiResult<object>>(jsonContent, new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
                    
                    if (apiResult != null && apiResult.IsSuccess)
                    {
                        return Json(new { success = true, message = "删除成功", data = apiResult.Data });
                    }
                    else
                    {
                        return Json(new { success = false, message = apiResult?.Msg ?? "删除失败" });
                    }
                }
                else
                {
                    return Json(new { success = false, message = $"删除失败：{response.StatusCode}" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"删除失败：{ex.Message}" });
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _httpClient?.Dispose();
            }
            base.Dispose(disposing);
        }
    }

    // 请求模型类
    public class ExportPlanRequest
    {
        public List<int> PlanIds { get; set; } = new List<int>();
        public string? OperateBy { get; set; }
    }

    public class BatchDeletePlanRequest
    {
        public List<int> PlanIds { get; set; } = new List<int>();
        public string? OperateBy { get; set; }
    }
} 